import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int[] a = { 12, 34, 47, 68, 91 };
        System.out.println("请输入要查找的数字：");
        int destination = scan.nextInt();
        int back = binarySearchSSR(a, destination);

        if (back >= 0) {
            System.out.println("查找到下标为：" + back);
        } else {
            System.out.println("不存在该目标！！！");
        }

//以下为Java提供算法
        back = Arrays.binarySearch(a, destination);

        if (back >= 0) {
            System.out.println("查找到下标为：" + back);
        } else {
            System.out.println("不存在该目标！！！");
        }
    }

    public static int binarySearchSSR(int[] a, int number) {
        int left = 0;
        int right = a.length;

        while (left <= right) {
            if (a[(left + right) / 2] < number) {
                left = (left + right) / 2 + 1;
            } else if (a[(left + right) / 2] > number) {
                right = (left + right) / 2 - 1;
            } else {
                return (left + right) / 2;
            }
        }

        return -1;
    }
}
